<?php

namespace web\addons\controller;

/**
 * 插件勾子抽象父类。
 * @author lcj
 */
abstract class AddonHook {

    protected $view = null;
    public $addon_path = '';
    public $config_file = '';
    protected $brand_id = '';
    private $addon_name = '';

    public function __construct($brand_id = null) {
        $this->brand_id = $brand_id;
        $this->view = new \think\View();
        $this->addon_name = $this->getName();
        $this->addon_path = './addons/' . $this->addon_name . '/';
        $TMPL_PARSE_STRING = config('view_replace_str');
        $TMPL_PARSE_STRING['__ADDON_NAME__'] = $this->addon_name;
        config('view_replace_str', $TMPL_PARSE_STRING);
        if (is_file($this->addon_path . 'config.php')) {
            $this->config_file = $this->addon_path . 'config.php';
        }
    }

    public function display($template = '', $vars = [], $replace = [], $config = [], $renderContent = false) {
        $config = config('template');
        $template = ADDONS_PATH . $this->addon_name . DS . MODULE_NAME . DS . 'view' . DS . 'hook' . DS . $template . '.' . ltrim($config['view_suffix'], '.');
        echo $this->view->fetch($template, $vars, $replace, $config, $renderContent);
    }

    /**
     * 模板变量赋值
     * @access protected
     * @param mixed $name 要显示的模板变量
     * @param mixed $value 变量的值
     * @return Action
     */
    final protected function assign($name, $value = '') {
        $this->view->assign($name, $value);
        return $this;
    }

    final public function getName() {
        $class = get_class($this);
        return \think\Loader::parseName(substr($class, strrpos($class, '\\') + 1, -4), 0);
    }

    /**
     * 获取插件的配置数组
     */
    final public function getConfig($name = '') {
        static $_config = array();
        if (empty($name)) {
            $name = $this->getName();
        }
        if (isset($_config[$name])) {
            return $_config[$name];
        }
        $m = new \web\common\model\sys\AddonsModel();
        $config = $m->getConfigData($name);
        if ($config) {
            $config = json_decode($config[0], true);
        } else {
            $temp_arr = include $this->config_file;
            foreach ($temp_arr as $key => $value) {
                if ($value['type'] == 'group') {
                    foreach ($value['options'] as $gkey => $gvalue) {
                        foreach ($gvalue['options'] as $ikey => $ivalue) {
                            $config[$ikey] = $ivalue['value'];
                        }
                    }
                } else {
                    $config[$key] = $temp_arr[$key]['value'];
                }
            }
        }
        $_config[$name] = $config;
        return $config;
    }

}
